package com.example.tms.controller;

import com.example.tms.bean.*;
import com.example.tms.mapper.*;
import com.example.tms.tools.GlobalParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * 订单管理
 */
@RestController
public class OrderController {

    private final OrderMapper orderMapper;
    private final RoadVMapper roadVMapper;
    private final RoadMapper roadMapper;
    private final CstmrMapper cstmrMapper;
    private final AreaMapper areaMapper;
    private final WaybillMapper waybillMapper;
//    private final CycleMapper cycleMapper;

    @Autowired
    public OrderController(OrderMapper orderMapper, RoadVMapper roadVMapper, RoadMapper roadMapper, CstmrMapper cstmrMapper, AreaMapper areaMapper, WaybillMapper waybillMapper) {
       this.orderMapper = orderMapper;
       this.roadVMapper = roadVMapper;
       this.roadMapper = roadMapper;
       this.cstmrMapper = cstmrMapper;
       this.areaMapper = areaMapper;
       this.waybillMapper = waybillMapper;
//       this.cycleMapper = cycleMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //查询订单信息列表
    @RequestMapping(value = "order",method = RequestMethod.GET)
    public ReturnInfo getOrderList(@RequestParam(required = false, defaultValue = "") String khjc,
                                   @RequestParam(required = false, defaultValue = "") String khzjm,
                                   @RequestParam(required = false, defaultValue = "") String xlmc,
                                   @RequestParam(required = false, defaultValue = "") String xlzjm,
                                   @RequestParam(required = false, defaultValue = "") String qymc,
                                   @RequestParam(required = false, defaultValue = "") String qyzjm,
                                   @RequestParam(required = false, defaultValue = "") String ddh,
                                   @RequestParam(required = false, defaultValue = "") String ddzt,
                                   @RequestParam(required = false, defaultValue = "") String qsrq,
                                   @RequestParam(required = false, defaultValue = "") String jsrq,
                                   @RequestParam(required = false, defaultValue = "") String xq){
        List<OrderMgmt> result = orderMapper.findAll((Root<OrderMgmt> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder)->{
            List<Predicate> list = new ArrayList<>();
            if(!khjc.equals("")){
                list.add(criteriaBuilder.like(root.get("khjc").as(String.class), "%" + khjc + "%"));
            }
            if(!khzjm.equals("")){
                list.add(criteriaBuilder.like(root.get("khzjm").as(String.class), "%" + khzjm + "%"));
            }
            if(!xlmc.equals("")){
                list.add(criteriaBuilder.like(root.get("xlmc").as(String.class), "%" + xlmc + "%"));
            }
            if(!xlzjm.equals("")){
                list.add(criteriaBuilder.like(root.get("xlzjm").as(String.class), "%" + xlzjm + "%"));
            }
            if(!qymc.equals("")){
                list.add(criteriaBuilder.like(root.get("qymc").as(String.class), "%" + qymc + "%"));
            }
            if(!qyzjm.equals("")){
                list.add(criteriaBuilder.like(root.get("qyzjm").as(String.class), "%" + qyzjm + "%"));
            }
            if(!ddh.equals("")){
                list.add(criteriaBuilder.like(root.get("ddh").as(String.class), "%" + ddh + "%"));
            }
            if(!ddzt.equals("")){
                list.add(criteriaBuilder.like(root.get("ddzt").as(String.class), "%" + ddzt + "%"));
            }
            if(!qsrq.equals("")){
                list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("ddrq").as(String.class), qsrq));
            }
            if(!jsrq.equals("")){
                list.add(criteriaBuilder.lessThanOrEqualTo(root.get("ddrq").as(String.class), jsrq));
            }
            if(!xq.equals("")){
                list.add(criteriaBuilder.equal(root.get("xingqi").as(String.class), xq));
            }
            list.add(criteriaBuilder.equal(root.get("sfcz").as(Boolean.class), true));
            Predicate[] p = new Predicate[list.size()];
            criteriaQuery.where(criteriaBuilder.and(list.toArray(p)));
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get("ddrq")),criteriaBuilder.desc(root.get("qymc")));
            return criteriaQuery.getRestriction();
        });
        return ReturnInfo.info2(result);
    }

    //查询订单信息
    @RequestMapping(value = "order/{ddid}",method = RequestMethod.GET)
    public OrderMgmt getOrderInfo(@PathVariable String ddid){
        return orderMapper.findByDdid(ddid);
    }

    //生成订单
    @RequestMapping(value = "order/{ddrq}",method = RequestMethod.POST)
    public ReturnInfo creatOrder(@PathVariable String ddrq){
        String b;
        if(!orderMapper.findByDdrqAndSfscdd(ddrq,true).toString().equals("[]")){
            b = "该天订单已生成！";
        }else {
            String week = GlobalParam.getWeek(ddrq);
            if(week.equals("星期格式错误！")){
                return ReturnInfo.info1(week);
            }
//            String ddh = ddrq.replaceAll("-","");
//            List<RoadView> result = roadVMapper.findBySfcz(true);
            List<RoadView> result = roadVMapper.findAll((Root<RoadView> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder)->{
                List<Predicate> list = new ArrayList<>();
                switch (week){
                    case "星期一":
                        list.add(criteriaBuilder.equal(root.get("yxzqzhouyi").as(Boolean.class), true));
                        break;
                    case "星期二":
                        list.add(criteriaBuilder.equal(root.get("yxzqzhouer").as(Boolean.class), true));
                        break;
                    case "星期三":
                        list.add(criteriaBuilder.equal(root.get("yxzqzhousan").as(Boolean.class), true));
                        break;
                    case "星期四":
                        list.add(criteriaBuilder.equal(root.get("yxzqzhousi").as(Boolean.class), true));
                        break;
                    case "星期五":
                        list.add(criteriaBuilder.equal(root.get("yxzqzhouwu").as(Boolean.class), true));
                        break;
                    case "星期六":
                        list.add(criteriaBuilder.equal(root.get("yxzqzhouliu").as(Boolean.class), true));
                        break;
                    case "星期日":
                        list.add(criteriaBuilder.equal(root.get("yxzqzhouri").as(Boolean.class), true));
                        break;
                    default:
                        break;
                }
                list.add(criteriaBuilder.equal(root.get("sfcz").as(Boolean.class), true));
                Predicate[] p = new Predicate[list.size()];
                criteriaQuery.where(criteriaBuilder.and(list.toArray(p)));
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("lasttime")));
                return criteriaQuery.getRestriction();
            });
            for(RoadView roadView : result){
                OrderMgmt orderMgmt = new OrderMgmt(roadView);
                orderMgmt.setDdrq(ddrq);
                orderMgmt.setXingqi(week);
                String ddh = ddrq.replaceAll("-","");
                long i = orderMapper.countByDdrq(ddrq);
                orderMgmt.setDdh(ddh+GlobalParam.getDdh(i));
                orderMapper.save(orderMgmt);
            }
//            for (RoadView roadView : result) {
//                CycleInfo cycleInfo = null;
//                switch (week){
//                    case "星期日":
//                        cycleInfo = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(roadView.getXlid(),"周日",ddrq);
//                        break;
//                    case "星期一":
//                        cycleInfo = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(roadView.getXlid(),"周一",ddrq);
//                        break;
//                    case "星期二":
//                        cycleInfo = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(roadView.getXlid(),"周二",ddrq);
//                        break;
//                    case "星期三":
//                        cycleInfo = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(roadView.getXlid(),"周三",ddrq);
//                        break;
//                    case "星期四":
//                        cycleInfo = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(roadView.getXlid(),"周四",ddrq);
//                        break;
//                    case "星期五":
//                        cycleInfo = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(roadView.getXlid(),"周五",ddrq);
//                        break;
//                    case "星期六":
//                        cycleInfo = cycleMapper.findTop1ByXlidAndYxzqAndYxrqLessThanEqualOrderByTjsjDesc(roadView.getXlid(),"周六",ddrq);
//                        break;
//                    default:
//                        break;
//                }
//                if(cycleInfo!=null&&cycleInfo.getSfyx()){
//                    OrderMgmt orderMgmt = new OrderMgmt(roadView);
//                    orderMgmt.setDdrq(ddrq);
//                    long i = orderMapper.countByDdrq(ddrq);
//                    orderMgmt.setDdh(ddh + GlobalParam.getDdh(i));
//                    orderMapper.save(orderMgmt);
//                }
//            }
            b = "订单生成成功！";
            logger.info("日期"+ddrq+" "+week+"  订单已生成！");
        }
        return ReturnInfo.info1(b);
    }

    //生成零散订单/加车
    @RequestMapping(value = "order",method = RequestMethod.POST)
    public List<Map<String,Object>> saveOrder(@RequestBody OrderMgmt orderMgmt){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(orderMapper.findByDdidAndSfcz(orderMgmt.getDdid(),true)==null){//生成零散订单
            if(cstmrMapper.findByKhidAndSfcz(orderMgmt.getKhid(),true)==null){
                map.put("khid","1");
            }
            if(areaMapper.findByQyidAndSfcz(orderMgmt.getQyid(),true)==null){
                map.put("qyid","1");
            }
            if(roadMapper.findByXlidAndSfcz(orderMgmt.getXlid(),true)==null){
                map.put("xlid","1");
            }
            if(!orderMgmt.getHwsl().equals("")&&!checkInteger(orderMgmt.getHwsl())){
                map.put("hwsl","0");
            }
            if(!orderMgmt.getYunfei().equals("")&&!checknumber(orderMgmt.getYunfei())){
                map.put("yunfei","0");
            }
            if(!orderMgmt.getGls().equals("")&&!checknumber(orderMgmt.getGls())){
                map.put("gls","0");
            }
            if(!orderMgmt.getYdj().equals("")&&!checknumber(orderMgmt.getYdj())){
                map.put("ydj","0");
            }
            list.add(map);
            if(map.isEmpty()){
                String ddrq = GlobalParam.getSRq();
                orderMgmt.setDdrq(ddrq);
                orderMgmt.setXingqi(GlobalParam.getWeek(ddrq));
                String ddh = ddrq.replaceAll("-","");
                long i = orderMapper.countByDdrq(ddrq);
                orderMgmt.setDdh(ddh+GlobalParam.getDdh(i));
                CstmrInfo cstmrInfo = cstmrMapper.findByKhid(orderMgmt.getKhid());
                orderMgmt.setKhjc(cstmrInfo.getKhjc());
                orderMgmt.setKhzjm(cstmrInfo.getKhzjm());
                AreaInfo areaInfo = areaMapper.findByQyidAndSfcz(orderMgmt.getQyid(), true);
                orderMgmt.setQymc(areaInfo.getQymc());
                orderMgmt.setZjm(areaInfo.getZjm());
                RoadInfo roadInfo = roadMapper.findByXlid(orderMgmt.getXlid());
                orderMgmt.setXlmc(roadInfo.getXlmc());
                orderMgmt.setXlzjm(roadInfo.getXlzjm());
                orderMgmt.setDdlx("零散订单");
                orderMgmt.setSfcz(true);
                orderMgmt.setSfscdd(false);
                orderMgmt.setDdid(null);
                orderMapper.save(orderMgmt);
                logger.info("生成零散订单"+orderMgmt.toString());
            }
        }else {
            if(orderMgmt.getDdid()==null||orderMgmt.getDdid().equals("")){
                map.put("ddid", "0");
            }
            if(!orderMgmt.getHwsl().equals("")&&!checkInteger(orderMgmt.getHwsl())){
                map.put("hwsl","0");
            }
            if(!orderMgmt.getYunfei().equals("")&&!checknumber(orderMgmt.getYunfei())){
                map.put("yunfei","0");
            }
            if(!orderMgmt.getGls().equals("")&&!checknumber(orderMgmt.getGls())){
                map.put("gls","0");
            }
            if(!orderMgmt.getYdj().equals("")&&!checknumber(orderMgmt.getYdj())){
                map.put("ydj","0");
            }
            list.add(map);
            if(map.isEmpty()){
                String ddrq = GlobalParam.getSRq();
                orderMgmt.setDdrq(ddrq);
                String ddh = ddrq.replaceAll("-","");
                long i = orderMapper.countByDdrq(ddrq);
                orderMgmt.setDdh(ddh+GlobalParam.getDdh(i));
                orderMgmt.setDdlx("加车单");
                orderMgmt.setSfcz(true);
                orderMgmt.setSfscdd(false);
                orderMgmt.setDdid(null);
                orderMapper.save(orderMgmt);
                logger.info("生成加车单"+orderMgmt.toString());
            }
        }
        return list;
    }

    //编辑订单
    @RequestMapping(value = "order",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateOrder(@RequestBody OrderMgmt orderMgmt){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(orderMgmt.getDdid()==null||orderMgmt.getDdid().equals("")){
            map.put("ddid", "0");
        }
        if(!orderMgmt.getHwsl().equals("")&&!checkInteger(orderMgmt.getHwsl())){
            map.put("hwsl","0");
        }
        if(!orderMgmt.getYunfei().equals("")&&!checknumber(orderMgmt.getYunfei())){
            map.put("yunfei","0");
        }
        if(!orderMgmt.getGls().equals("")&&!checknumber(orderMgmt.getGls())){
            map.put("gls","0");
        }
        if(!orderMgmt.getYdj().equals("")&&!checknumber(orderMgmt.getYdj())){
            map.put("ydj","0");
        }
        list.add(map);
        if(map.isEmpty()){
            orderMapper.UpdateByDdid(orderMgmt.getDdid(),orderMgmt.getHuowu(),orderMgmt.getHwsl(),orderMgmt.getYdj(),orderMgmt.getYunfei(),orderMgmt.getGls());
            logger.info("编辑订单"+orderMgmt.toString());
        }
        return list;
    }

    //发布订单
    @RequestMapping(value = "order/{ddid}",method = RequestMethod.PUT)
    public ReturnInfo issueOrder(@PathVariable String ddid){
        String b;
        if(orderMapper.findByDdid(ddid)==null){
            b = "订单不存在！";
        }else {
            OrderMgmt orderMgmt = orderMapper.findByDdid(ddid);
            WaybillMgmt waybillMgmt = new WaybillMgmt(orderMgmt);
            try{
                waybillMapper.save(waybillMgmt);
                orderMapper.IssueByDdid(ddid);
                b = "订单发布成功！";
                logger.info("发布订单成功"+ddid);
            }catch (NullPointerException e){
                b = "订单发布失败！";
                logger.info("发布订单失败"+ddid);
            }
        }
        return ReturnInfo.info1(b);
    }

    //删除订单
    @RequestMapping(value = "order/{ddid}",method = RequestMethod.DELETE)
    public ReturnInfo deleteOrder(@PathVariable String ddid){
        String b;
        if(orderMapper.findByDdid(ddid)==null){
            b = "删除失败！";
        }else {
            orderMapper.DeleteByDdid(ddid);
            b = "删除成功！";
            logger.info("删除订单成功"+ddid);
        }
        return ReturnInfo.info1(b);
    }

    //检查整数
    private Boolean checkInteger(String integer){
        Boolean b = false;
        if(integer.matches("^[1-9][0-9]{0,14}$")){
            b = true;
        }
        return b;
    }

    //检查数
    private Boolean checknumber(String number){
        Boolean b = false;
        if(number.matches("^[0-9.]{0,14}$")){
            b = true;
        }
        return b;
    }
}